package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"os"
)

var v *viper.Viper

func init() {
	v = viper.New()
	dir, _ := os.Getwd()
	v.SetConfigName("config_change")
	v.AddConfigPath(dir)
	v.AddConfigPath(".")
	v.AddConfigPath(dir + "/watch_change")
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) { // 配置文件发生变更的回调。
		// @see  golang 通过 fsnotify 监控文件，并通过文件变化重启程序 - 怀素真 https://www.cnblogs.com/jkko123/p/7256927.html
		fmt.Println("Config file changed:", e.String())
		v.ReadInConfig() //立即读入配置
	})
	v.ReadInConfig()
}
func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		//param := c.Query("version")
		//fmt.Println("version input: " + param)
		//if param != "" {
		//	fmt.Println("设置默认version:" + param)
		//	v.SetDefault("current.version", param)
		//}
		version := v.GetString("current.version")
		fmt.Println("获取配置version:" + version)
		c.String(200, "version is %s", version)
	})
	r.Run(":8999")
}
